package com.itheima.tlias.controller;


import com.itheima.tlias.pojo.Emp;
import com.itheima.tlias.pojo.LoginInfo;
import com.itheima.tlias.pojo.Result;
import com.itheima.tlias.service.EmpService;
import com.itheima.tlias.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
public class LoginController {
    @Autowired
    private EmpService empService;
    @Autowired
    private JwtUtils jwtUtils;


    @PostMapping("/login")
    public Result login(@RequestBody Emp emp, HttpServletRequest request) {
        log.info("员工来登录啦 , {}", emp);

        // 1️. 获取 session 中存储的验证码答案
        String realCaptcha = (String) request.getSession().getAttribute("captcha");

//        // 2. 验证验证码是否为空或错误
//        if (realCaptcha == null || !realCaptcha.equalsIgnoreCase(emp.getCaptcha())) {
//            return Result.error("验证码错误");
//        }

        LoginInfo loginInfo = empService.login(emp);
        log.info("{}",loginInfo);
        if (loginInfo == null) {
            return Result.error("用户名或密码错误");
        }
//        Map<String, Object> claims = new HashMap<>();
//        claims.put("id", loginInfo.getId());
        //登录成功生成JWT令牌
//        String token = JwtUtils.CreateJWT(claims);
        String token = jwtUtils.createToken(loginInfo.getId());
        loginInfo.setToken(token);
        log.info("生成令牌成功, {}", loginInfo);
        return Result.success(loginInfo);
    }


}